/**   
 *    
 * 项目名称：SmartKungFu   
 * 类名称：MstOrderController   
 * 类描述： 订单控制层  
 * 创建人：zhangl  
 * 创建时间：2016年10月17日 上午10:31:01   
 * 修改人：zhangl   
 * 修改时间：2016年10月17日 上午10:31:01   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.controller;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.github.miemiedev.mybatis.paginator.domain.PageList;
import com.github.miemiedev.mybatis.paginator.domain.Paginator;
import com.lst.common.BaseController;
import com.lst.common.CommonEnum;
import com.lst.exception.MyException;
import com.lst.model.FolPara;
import com.lst.model.MstButton;
import com.lst.model.MstOrder;
import com.lst.model.MstUser;
import com.lst.model.OrderDetail;
import com.lst.model.vo.MstOrderVo;
import com.lst.service.MstButtonService;
import com.lst.service.MstOrderService;
import com.lst.service.OrderDetailService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstOrderController
 * @Description:订单控制层
 * @author zhangl
 * @date 2016年10月17日 上午10:31:01
 * 
 */
@Controller
@RequestMapping("mstOrderController")
public class MstOrderController extends BaseController {

	@Autowired
	private MstOrderService mstOrderService;

	@Autowired
	private OrderDetailService orderDetailService;

	@Autowired
	private MstButtonService mstButtonService;

	/**
	 * 
	 * @Title: list
	 * @Description:页面加载
	 * @param @param request
	 * @param @param response
	 * @param @param menuId
	 * @param @param page
	 * @param @param rows
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @param rolName
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return ModelAndView 返回类型
	 */

	@RequestMapping(value = "/list")
	public ModelAndView list(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = true) int menuId,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGE) int page,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) int rows,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che,
			@RequestParam(required = false, defaultValue = "") String rolName)
					throws MyException {
		Date startDate = new Date();
		logger.info("list begin: " + startDate);

		FolPara folPara = new FolPara();
		folPara.setMenuId(menuId);
		folPara.setPage(page);
		folPara.setRows(rows);
		folPara.setRolName(rolName);

		MstUser mstUser = this.getMySession().getMstUser();
		List<MstButton> btns = CommonUtils.readPermissionWithBtn(menuId,
				mstUser, mstButtonService);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_ORDER
				+ "order_list");
		mv.addObject("btns", btns);
		mv.addObject("folPara", folPara);

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("list end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	/**
	 * 
	 * @Title: queryList
	 * @Description:queryList
	 * @param @param page
	 * @param @param pageSize
	 * @param @param rolName
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return Object 返回类型
	 */
	@RequestMapping(value = "/queryList")
	@ResponseBody
	public Object queryList(
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGE) Integer page,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEMPAGE_PAGESIZE) Integer pageSize,
			@RequestParam(required = false, defaultValue = "") String sort,
			@RequestParam(required = false, defaultValue = CommonEnum.SYSTEM_ORDER_DESC) String order,
			@RequestParam(required = false, defaultValue = "") String minDate,
			@RequestParam(required = false, defaultValue = "") String maxDate,
			@RequestParam(required = false, defaultValue = "") String account,
			@RequestParam(required = false, defaultValue = "") String mobileNo,
			@RequestParam(required = false, defaultValue = "") String orderNo)
					throws MyException {
		Date startDate = new Date();
		logger.info("queryList begin: " + startDate);

		Map<String, Object> reqMap = new HashMap<String, Object>();
		//reqMap.put("isDeleted", 0);
		reqMap.put("enabled", 1);

		if (StringUtils.isEmpty(sort)) {
			reqMap.put("orderByClause", "o.createdate desc");
		} else {
			reqMap.put("orderByClause", sort + " " + order);
		}

		if (!StringUtils.isBlank(account)) {
			reqMap.put("_account", account.trim());
		}

		if (!StringUtils.isBlank(mobileNo)) {
			reqMap.put("_mobileno", mobileNo.trim());
		}

		if (!StringUtils.isBlank(orderNo)) {
			reqMap.put("_orderNo", orderNo.trim());
		}

		if (!StringUtils.isBlank(minDate) && !StringUtils.isBlank(maxDate)) {
			try {
				if (DateUtil.parse(minDate).after(DateUtil.parse(maxDate))) {
					reqMap.put("minDate", maxDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", minDate + DateUtil.END_DATE_HMS);
				} else {
					reqMap.put("minDate", minDate + DateUtil.START_DATE_HMS);
					reqMap.put("maxDate", maxDate + DateUtil.END_DATE_HMS);
				}
			} catch (ParseException e) {
				logger.error("queryList error: ", e);
			}
		}

		PageBounds pageBounds = new PageBounds(page, pageSize);
		List<MstOrderVo> list = mstOrderService.queryByList(reqMap, pageBounds);

		Map<String, Object> odMap = new HashMap<String, Object>();
		PageBounds _pageBounds = new PageBounds();
		for (MstOrderVo mstOrderVo : list) {
			// 获取订单详情
			odMap.put("orderId", mstOrderVo.getId());
			odMap.put("enabled", true);
			odMap.put("isDeleted", false);

			List<OrderDetail> ods = orderDetailService.queryByList(odMap,_pageBounds);

			mstOrderVo.setOds(ods);
		}

		PageList<MstOrderVo> pageList = (PageList<MstOrderVo>) list;
		Paginator paginator = pageList.getPaginator();

		HashMap<String, Object> indexPages = new HashMap<String, Object>();
		indexPages.put("total", paginator.getTotalCount());
		indexPages.put("rows", list);

		logger.info("queryList end run(s): "
				+ DateUtil.calLastedTime(startDate));

		return indexPages;
	}

	/**
	 * 
	 * @Title: edit
	 * @Description: 编辑页面
	 * @param @param id
	 * @param @param index_exp
	 * @param @param index_che
	 * @param @return 设定文件
	 * @return ModelAndView 返回类型
	 */
	@RequestMapping(value = "/edit")
	public ModelAndView edit(
			@RequestParam(required = false) String id,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_EXP) String index_exp,
			@RequestParam(required = false, defaultValue = CommonEnum.MENU_STYLE_INDEX_CHE) String index_che) {
		Date startDate = new Date();
		logger.info("edit begin: " + startDate);

		ModelAndView mv = new ModelAndView(CommonEnum.FORWARD_VIEW_MAIN_ORDER
				+ "order_edit");

		if (!StringUtils.isBlank(id)) {
			MstOrder mstOrder = mstOrderService.selectByPrimaryKey(Integer
					.parseInt(id));
			mv.addObject("mstOrder", mstOrder);
		}

		mv.addObject("MENU_STYLE_INDEX_EXP", index_exp);
		mv.addObject("MENU_STYLE_INDEX_CHE", index_che);

		logger.info("edit end run(s): " + DateUtil.calLastedTime(startDate));

		return mv;
	}

	@RequestMapping(value = "/update")
	@ResponseBody
	public String update(HttpServletRequest request) {
		String back = "";
		try {
			String id = request.getParameter("id");
			Map<String, Object> odMap = new HashMap<String, Object>();

			odMap.put("orderId", Integer.valueOf(id));
			odMap.put("enabled", true);
			odMap.put("isDeleted", false);

			List<OrderDetail> ods = orderDetailService.queryByList(odMap,
					new PageBounds());

			orderDetailService.updateStatus(ods, getMySession().getMstUser()
					.getId());

			back = "success";
		} catch (Exception e) {
			back = "error";
			logger.error("order update error:", e);
		}
		return back;
	}

	/**
	 * 
	 * @Title: save
	 * @Description:save
	 * @param @param mstrole
	 * @param @param folPara
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return String 返回类型
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public String save(@Valid MstOrder mstOrder, BindingResult br,
			FolPara folPara) throws MyException {
		Date startDate = new Date();
		logger.info("save begin: " + startDate);

		MstUser mstUser = this.getMySession().getMstUser();

		try {
			// 拦截非法请求参数
			if (br.hasErrors()) {
				List<ObjectError> ers = br.getAllErrors();
				logger.info("--------------form parameter error start-----------------------");

				for (ObjectError er : ers) {
					logger.info("save faile with parameter illegal: "
							+ er.getDefaultMessage());
				}

				logger.info("--------------form parameter error end-----------------------");
			} else {
				if (mstOrder.getId() != null) {
					mstOrder.setUpdatedate(startDate);
					mstOrder.setUpdateuser(mstUser.getId());

					mstOrderService.updateByPrimaryKeySelective(mstOrder);
				} else {
					mstOrder.setEnabled(true);
					mstOrder.setIsdeleted(false);
					mstOrder.setCreatedate(startDate);
					mstOrder.setCreateuser(mstUser.getId());

					mstOrderService.insert(mstOrder);
				}
			}
		} catch (Exception e) {
			logger.error("save error: ", e);
		}

		StringBuffer sb = new StringBuffer("?");
		sb.append("menuId=" + folPara.getMenuId());
		sb.append("&page=" + folPara.getPage());
		sb.append("&rows=" + folPara.getRows());
		sb.append("&rolName=" + folPara.getRolName());
		
		sb.append("&index_exp=" + folPara.getIndex_exp());
		sb.append("&index_che=" + folPara.getIndex_che());

		logger.info("save end run(s):" + DateUtil.calLastedTime(startDate));

		return "redirect:list" + sb.toString();
	}

	/**
	 * 
	 * @Title: delList
	 * @Description: 批量删除
	 * @param @param request
	 * @param @param response
	 * @param @param ids
	 * @param @return
	 * @param @throws MyException 设定文件
	 * @return boolean 返回类型
	 */
	@RequestMapping("delList")
	@ResponseBody
	public boolean delList(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(required = true) String ids) throws MyException {
		Date startDate = new Date();
		logger.info("delList begin: " + startDate);

		boolean flag = false;

		MstUser mstUser = this.getMySession().getMstUser();

		Map<String, Object> reqMap = new HashMap<String, Object>();
		reqMap.put("ids", ids);
		reqMap.put("updateUser", mstUser.getId());

		try {
			mstOrderService.delList(reqMap);
			flag = true;
		} catch (Exception e) {
			logger.error("delList error: ", e);
		}

		logger.info("delList end run(s): " + DateUtil.calLastedTime(startDate));

		return flag;
	}
}
